# imagecap module (wxWidgets based) for SkyTanx

import wx

# We have to initialize wxpython first and only once
app = wx.App(False)

class ImageCap:
	# Initializes an ImageCap object
	#  width: width of desired snapshot
	#  height: height of desired snapshot
	#  x: x-offset of desired snapshot
	#  y: y-offset of desired snapshot
	# NOTE: image is copied from screen without scaling
	def __init__(self, width, height, x = 0, y = 0):
		# Save member fields for later
		self.x = x
		self.y = y
		self.width = width
		self.height = height
		
		# Initialize screen context and clip arguments if too large
		self.screen = wx.ScreenDC()
		actualWidth, actualHeight = self.screen.GetSizeTuple()
		if x >= actualWidth:
			# The requested picture has no area!
			raise ValueError("x-offset too large for current screen resolution")
		if y >= actualHeight:
			# The requested picture has no area!
			raise ValueError("y-offset too large for current screen resolution")
		if x + width > actualWidth:
			width = actualWidth - x
		if y + height > actualHeight:
			height = actualHeight - y
		
		# Initialize the bitmap memory and context will use to save the screen
		self.bitmap = wx.EmptyBitmap(width, height, -1) # -1->use current depth
		self.memDC = wx.MemoryDC()
	
	# Copies screen into bitmap's memory. Should only be used internally.
	def blit(self):
		# Copy screen into bitmap through memory context
		self.memDC.SelectObject(self.bitmap)
		self.memDC.Blit(0, 0, self.width, self.height, self.screen, self.x, self.y)
		self.memDC.SelectObject(wx.NullBitmap) # flushes context to bitmap mem.
		
	# Captures screen and saves to file.
	# See wx.Bitmap documentation for information on type parameter.
	def save(self, path, type = wx.BITMAP_TYPE_BMP):
		self.blit()
		self.bitmap.SaveFile(path, type)
		
	# Captures screen and returns raw data as string.
	def capture(self):
		self.blit()
		return self.bitmap.ConvertToImage().GetData();
		
